package com.xiamao.jdt.controller;

import com.alibaba.fastjson2.JSON;
import com.xiamao.jdt.entity.*;
import com.xiamao.jdt.service.ChargingDeviceService;
import com.xiamao.jdt.service.MaxChargePercentRedisService;
import com.xiamao.jdt.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/device")
public class DeviceInfoController {

    private final Logger logger = LoggerFactory.getLogger(DeviceInfoController.class);

    @Autowired
    private ChargingDeviceService chargingDeviceService;

    @Autowired
    private MaxChargePercentRedisService maxChargePercentRedisService;

    // 进程管理变量
    private Process monitorProcess = null;

    // 静态对象用于存储接收到的数据
    private static DeviceInfo storedDeviceInfo = null;
    private static ChargeInfo storedChargeInfo = null;

    @PostMapping("/info")
    public Result<String> receiveDeviceInfo(@RequestBody DeviceInfo deviceInfo) {
        logger.info("收到了设备信息:{}", JSON.toJSONString(deviceInfo));
        storedDeviceInfo = deviceInfo;
        return Result.success("设备信息已成功接收并存储");
    }

    @GetMapping("/info")
    public Result<DeviceInfo> getStoredDeviceInfo() {
        if (storedDeviceInfo != null) {
            return Result.success(storedDeviceInfo);
        } else {
            return Result.error(500, "未找到设备信息");
        }
    }

    @PostMapping("/charge-info")
    public Result<String> receiveChargeInfo(@RequestBody ChargeInfo chargeInfo) {
        logger.info("收到了充电信息:{}", JSON.toJSONString(chargeInfo));
        storedChargeInfo = chargeInfo;
        return Result.success("充电信息已成功接收并存储");
    }

    @GetMapping("/charge-info")
    public Result<ChargeInfo> getStoredChargeInfo() {
        if (storedChargeInfo != null) {
            return Result.success(storedChargeInfo);
        } else {
            return Result.error(500, "未找到充电信息");
        }
    }

    /**
     * 设置指定设备和接口的最大充电百分比
     *
     * @param deviceId    设备ID
     * @param interfaceId 接口ID
     * @param maxPercent  最大充电百分比
     * @return 操作结果
     */
    @PostMapping("/max-charge-percent")
    public Result<String> setMaxChargePercent(
            @RequestParam(required = false) String carNo,
            @RequestParam int deviceId,
            @RequestParam int interfaceId,
            @RequestParam int maxPercent) {
        // 验证参数
        if (maxPercent < 0 || maxPercent > 100) {
            return Result.error(500, "最大充电百分比必须在0-100之间");
        }
        // 构造键值
        String key = deviceId + ":" + interfaceId;
        String carKey = deviceId + ":" + interfaceId + ":" + carNo;
        // 存储设置到Redis中
        maxChargePercentRedisService.setMaxChargePercent(key, maxPercent);
        maxChargePercentRedisService.setCarNoChargePercent(carKey, maxPercent);
        return Result.success("设备ID为 " + deviceId + " 且接口ID为 " + interfaceId +
                " 的最大充电百分比已设置为 " + maxPercent + "%");
    }

    @PostMapping("/clear-max-charge-percent")
    public Result<String> unSetMaxChargePercent(
            @RequestParam(required = false) String carNo,
            @RequestParam int deviceId,
            @RequestParam int interfaceId) {
        // 构造键值
        String key = deviceId + ":" + interfaceId;
        String carKey = deviceId + ":" + interfaceId + ":" + carNo;
        // 存储设置到Redis中
        maxChargePercentRedisService.unSetMaxChargePercent(key);
        return Result.success("设备ID为 " + deviceId + " 且接口ID为 " + interfaceId + " 的最大充电百分比已清除。");
    }

    /**
     * 查询设备充电信息并按指定维度排序
     *
     * @return 排序后的设备充电信息列表
     */
    @GetMapping("/charging-device-info")
    public Result<List<ChargingDeviceInfo>> getChargingDeviceInfo(final @RequestParam(defaultValue = "N") String isShowAll) {
        List<ChargingDeviceInfo> result = chargingDeviceService.processAndSortChargingDeviceInfo(isShowAll,
                storedDeviceInfo, storedChargeInfo, maxChargePercentRedisService.getAllMaxChargePercents());
        return Result.success(result);
    }


    @PostMapping("/cookie")
    public Result<String> saveCookies(@RequestBody CookieRequest request) {
        logger.info("收到了Cookie信息:{}", JSON.toJSONString(request));
        try {
            //将Cookie保存到本地文件cookie.txt下
            try (final FileWriter writer = new FileWriter("cookie.txt", false)) {
                for (final CookieRequest.CookieInfo cookie : request.getCookies()) {
                    writer.write(cookie.getName() + "=" + cookie.getValue() + "; ");
                }
                writer.write("\n");
            } catch (final IOException e) {
                return Result.error(500, "保存Cookie失败:" + e.getMessage());
            }
            return Result.success("Cookie保存成功");
        } catch (final Exception e) {
            return Result.error(500, "保存Cookie失败:" + e.getMessage());
        }
    }

    /**
     * 开启采集 - 启动Python监控脚本
     *
     * @return 操作结果
     */
    @PostMapping("/start-monitoring")
    public Result<String> startMonitoring() {
        try {
            if (monitorProcess != null && monitorProcess.isAlive()) {
                return Result.success("采集已经在运行中");
            }

            // 构建执行Python脚本的命令
            String[] command = {"python3", "./charge_station_monitor.py"};
            
            // 启动进程
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.inheritIO(); // 继承输入输出流，方便查看日志
            monitorProcess = processBuilder.start();
            
            return Result.success("采集已开启");
        } catch (Exception e) {
            logger.error("开启采集失败", e);
            return Result.error(500, "开启采集失败: " + e.getMessage());
        }
    }

    /**
     * 停止采集 - 结束Python监控脚本
     *
     * @return 操作结果
     */
    @PostMapping("/stop-monitoring")
    public Result<String> stopMonitoring() {
        try {
            if (monitorProcess == null || !monitorProcess.isAlive()) {
                return Result.success("采集未在运行");
            }

            // 结束进程
            monitorProcess.destroy();
            monitorProcess.waitFor(); // 等待进程完全结束
            
            monitorProcess = null;
            return Result.success("采集已停止");
        } catch (Exception e) {
            logger.error("停止采集失败", e);
            return Result.error(500, "停止采集失败: " + e.getMessage());
        }
    }


}